$(document).ready( function() {
  intervals.push(setInterval(updateLists, 500));
  intervals.push(setInterval(updateLogs, 500));
  $('input[type=button][value=run],input[type=button][value=stop]').bind('click', function() { submitForm($(this).parent());});
  initiateOrbit();
});

var actors = { peer : [], recipe_server:[], tracker : [], monitor:[]} 
var logs = []
clearIntervals = function() {
  for(i in intervals) {
    clearInterval(intervals[i]);
  }
  intervals = []
}
clearTimeouts = function() {
  for(i in intervals) {
    clearTimeout(timeouts[i]);
  }
  timeouts = []
}
var intervals = []
var timeouts = []
var stomp = null;
initiateOrbit = function() {  

  stomp = new STOMPClient();
  stomp.onopen = function() {
      console.log("Transport openned");
  };
  stomp.onclose = function(code) {
      console.log("Transport closed (code: " + code + ")");
  };
  stomp.onerror = function(error) {
      console.log("onerror: " + error);
  };
  stomp.onerrorframe = function(frame) {
      console.log("onerrorframe: " + frame.body);
  };
  stomp.onconnectedframe = function() {
      console.log("Connected as user ");
  };
  stomp.onmessageframe = function(frame) {      
      msg = JSON.parse(frame.body);
      actors.peer = msg.peers;
      actors.monitor = msg.monitors;
      actors.recipe_server = msg.recipe_servers;
      actors.tracker = msg.trackers;
      logs = msg.logs;            
  };
  stomp.sendmsg = function(method, args) {
      this.send(JSON.stringify({method:method,args:args, id:this.id}),'/server'); 
  }  
  stomp.id = getQueryVariable('id');  
  stomp.connect('localhost', 61613, '', '');
  stomp.rem_tries = 3;  
  stomp.subscribe_delayed = function() {    
    try {
      stomp.subscribe('/client/' + stomp.id);
      stomp.rem_tries = 3;
    } catch(e) {
      if(stomp.rem_tries == 0) {
        console.error("subscription failed");
      } else {
        stomp.rem_tries--;
        console.error("subscription failed, will try " + stomp.rem_tries + " more times");
        timeouts.push(setTimeout(stomp.subscribe_delayed, 2000));
      }      
    }
  }
  timeouts.push(setTimeout(stomp.subscribe_delayed, 2000));
};
onunload = function() { stomp.reset(); }
  

updateLogs = function() { 
    for(i in logs) {
        row = logs[i];
        record_str = ''
        for(i =0; i < row[2].length/80; ++i) {
          if(i > 0)
            record_str += "<br>";
          record_str += row[2].substring(100*i, 100*(i+1));
        }
        $('#log').prepend('<div class=log-message>' + 
                              '<span class=log-time>' + row[0] + '</span> ' + 
                              '<span class=log-thread>' +  row[1] + '</span> ' + 
                              '<span class=log-record>' + record_str +'</span>'+ 
                          '</div>');
    }
    logs = []
 }
submitForm = function(el) {  
  arr = el.serializeArray();
  data = {};
  method = '';
  for(i in arr) {    
    obj = arr[i];
    if(obj.name == 'name' && !obj.value) {
      alert('specify peer name');      
      return false;
    }
    if(obj.name == 'method') {
      method = obj.value;
    } else {
      data[obj.name] = obj.value;
    }
  }
  stomp.sendmsg(method,data);
  return false;
}

updatePeer = function(ind, peer) {
  if($('#peer-'+ind).length == 0) {
    peerDiv = document.createElement('div');
    $(peerDiv).attr('id', 'peer-' + ind);
    link = document.createElement('a');
    $(link).attr({'href' : 'http://'+document.domain+':' + peer.http_port, target:"_blank", class:'address'});    
    $(link).text(peer.name + '@' + peer.external_ip + ':' + peer.external_port);
    $(peerDiv).append(link);
    form = document.createElement('form');  
    hidden1 = document.createElement('input');
    $(hidden1).attr({type:'hidden', name:'method', value:'stop_peer'});
    hidden2 = document.createElement('input');
    $(hidden2).attr({type:'hidden', name:'ind', value:ind});
    button = document.createElement('input');
    $(button).attr({id:'peer-button-'+ind, type:'button', value:'stop'});
    $(button).click(function() { submitForm($(this).parent()); } );  
    $(form).append(hidden1);
    $(form).append(hidden2);
    $(form).append(button);
    $(peerDiv).append(form);
    $('#peers').append(peerDiv);
  } 
  if(!peer.isAlive) {
    $('#peer-button-'+ind).attr('disabled','disabled');
    $('#peer-button-'+ind).val('stopped');  
  }   
}

updateLists = function(ind, key, obj) {
  for(key in actors) {
    for(ind in actors[key]) {
      obj = actors[key][ind];
      if($('#' + key +'-'+ind).length == 0) {
        objDiv = document.createElement('div');
        $(objDiv).attr('id', key + '-' + ind);
        link = document.createElement('a');
        $(link).attr({'href' : 'http://'+document.domain+':' + obj.http_port, target:"_blank", class:'address'});    
        $(link).text(obj.name + '@' + obj.external_ip + ':' + obj.external_port);
        $(objDiv).append(link);
        form = document.createElement('form');  
        hidden1 = document.createElement('input');
        $(hidden1).attr({type:'hidden', name:'method', value:'stop_' + key});
        hidden2 = document.createElement('input');
        $(hidden2).attr({type:'hidden', name:'ind', value:ind});
        button = document.createElement('input');
        $(button).attr({id:key+ '-button-'+ind, type:'button', value:'stop'});
        $(button).click(function() { submitForm($(this).parent()); } );  
        $(form).append(hidden1);
        $(form).append(hidden2);
        $(form).append(button);
        $(objDiv).append(form);
        $('#' + key + 's').append(objDiv);
      } 
      if(!obj.isAlive) {
        $('#' + key +'-button-'+ind).attr('disabled','disabled');
        $('#' + key + '-button-'+ind).val('stopped');  
      }   
    }
  }

}
getQueryVariable = function(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return 'first';  
} 